package com.zhupanlin.service;

import com.zhupanlin.dao.UserDao;
import com.zhupanlin.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: 自定义 UserDetailService 实现
 * @date 2024/12/15 20:52
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    private final UserDao userDao;

    @Autowired
    public MyUserDetailService(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.loadUserByUsername(username);
        if (ObjectUtils.isEmpty(user)) {
            throw new RuntimeException("用户名不存在!");
        }
        user.setRoles(userDao.getRolesByUid(user.getId()));
        return user;
    }
}
